package com.vast.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vast.admin.entity.CompanyPaymentType;
import com.vast.admin.mapper.CompanyPaymentTypeMapper;
import com.vast.system.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CompanyPaymentTypeService extends ServiceImpl<CompanyPaymentTypeMapper, CompanyPaymentType> {

    /**
     * 批量保存
     * @param companyId
     * @param companyPaymentTypes
     */
    @Transactional
    public void saveCompanyPaymentTypes(Long companyId, List<CompanyPaymentType> companyPaymentTypes) {
        checkCompanyPaymentTypes(companyPaymentTypes);
        QueryWrapper<CompanyPaymentType> companyPaymentTypeQueryWrapper = new QueryWrapper<>();
        companyPaymentTypeQueryWrapper.eq(CompanyPaymentType.COL_COMPANY_ID, companyId);
        super.remove(companyPaymentTypeQueryWrapper);
        companyPaymentTypes.forEach(companyPaymentType -> companyPaymentType.setCompanyId(companyId));
        super.saveBatch(companyPaymentTypes);
    }

    /**
     * 检查区间是否全覆盖
     * @param companyPaymentTypes
     */
    private void checkCompanyPaymentTypes(List<CompanyPaymentType> companyPaymentTypes) {
        List<CompanyPaymentType> sortList = companyPaymentTypes.stream().sorted(Comparator.comparing(CompanyPaymentType::getStartAmount)).collect(Collectors.toList());
        CompanyPaymentType prev = null;
        for (CompanyPaymentType companyPaymentType : sortList) {
            if (prev == null) {
                if (companyPaymentType.getStartAmount() != 0) {
                    throw new BusinessException("合同金额区间不是从0开始");
                } else {
                    prev = companyPaymentType;
                }
            } else {
                if (prev.getEndAmount().doubleValue() != companyPaymentType.getStartAmount().doubleValue()) {
                    throw new BusinessException("合同金额区间未覆盖" + prev.getEndAmount() + "至" + companyPaymentType.getStartAmount());
                } else {
                    prev = companyPaymentType;
                }
            }
        }
    }

    /**
     * 合同金额获取付款金额
     * @param companyId
     * @param amount
     * @return
     */
    public Double getByAmount(Long companyId, Double amount) {
        QueryWrapper<CompanyPaymentType> companyPaymentTypeQueryWrapper = new QueryWrapper<>();
        companyPaymentTypeQueryWrapper.eq(CompanyPaymentType.COL_COMPANY_ID, companyId)
                .le(CompanyPaymentType.COL_START_AMOUNT, amount)
                .and(companyPaymentTypeQueryWrapper1 -> companyPaymentTypeQueryWrapper1
                        .gt(CompanyPaymentType.COL_END_AMOUNT, amount)
                        .or()
                        .eq(CompanyPaymentType.COL_END_AMOUNT, -1));
        List<CompanyPaymentType> companyPaymentTypes = super.list(companyPaymentTypeQueryWrapper);
        if (companyPaymentTypes == null || companyPaymentTypes.isEmpty()) {
            throw new BusinessException("合同付款金额计算失败，请联系系统管理员检查付款类型配置");
        }
        CompanyPaymentType companyPaymentType = companyPaymentTypes.get(0);
        if (companyPaymentType.getType() == 1) {
            return companyPaymentType.getAmount();
        } else {
            return new BigDecimal(amount)
                    .multiply(new BigDecimal(companyPaymentType.getPercent()).divide(new BigDecimal(1000)))
                    .setScale(2, RoundingMode.HALF_UP)
                    .doubleValue();
        }
    }

    /**
     * 阶梯付费方式
     * @param companyId
     * @param amount
     * @return
     */
    public Double getByStep(Long companyId, Double amount) {
        QueryWrapper<CompanyPaymentType> companyPaymentTypeQueryWrapper = new QueryWrapper<>();
        companyPaymentTypeQueryWrapper.eq(CompanyPaymentType.COL_COMPANY_ID, companyId)
                .le(CompanyPaymentType.COL_START_AMOUNT, amount)
                .orderByDesc(CompanyPaymentType.COL_START_AMOUNT);
        List<CompanyPaymentType> companyPaymentTypes = super.list(companyPaymentTypeQueryWrapper);
        if (companyPaymentTypes == null || companyPaymentTypes.isEmpty()) {
            throw new BusinessException("合同付款金额计算失败，请联系系统管理员检查付款类型配置");
        }
        boolean isFirst = true;
        BigDecimal result = new BigDecimal(0);
        for (CompanyPaymentType companyPaymentType : companyPaymentTypes) {
            if (companyPaymentType.getType() == 1) {
                result = result.add(new BigDecimal(companyPaymentType.getAmount()));
            } else {
                BigDecimal tmp = null;
                if (isFirst) {
                    tmp = new BigDecimal(amount).subtract(new BigDecimal(companyPaymentType.getStartAmount()));
                } else {
                    tmp = new BigDecimal(companyPaymentType.getEndAmount()).subtract(new BigDecimal(companyPaymentType.getStartAmount()));
                }
                result = result.add(tmp.multiply(new BigDecimal(companyPaymentType.getPercent()).divide(new BigDecimal(1000))));
            }
			isFirst = false;
        }
        return result.setScale(0, RoundingMode.HALF_UP).doubleValue();
    }

    /**
     * 企业id获取
     * @param companyId
     * @return
     */
    public List<CompanyPaymentType> getByCompanyId(Long companyId) {
        QueryWrapper<CompanyPaymentType> companyPaymentTypeQueryWrapper = new QueryWrapper<>();
        companyPaymentTypeQueryWrapper.eq(CompanyPaymentType.COL_COMPANY_ID, companyId);
        return super.list(companyPaymentTypeQueryWrapper);
    }

}
